from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.academic_year import AcademicYear as AcademicYearModel, AcademicYearInDB
from app.schemas.academic_year import AcademicYear as AcademicYearSchema, AcademicYearCreate, AcademicYearUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/academic-years", tags=["academic_years"])

@router.post("/create", response_model=APIResponse[AcademicYearSchema])
def create_academic_year(academic_year: AcademicYearCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating academic year with year_code: {academic_year.year_code}")
    
    # 检查学年编码和学期是否已存在
    db_academic_year = db.query(AcademicYearModel).filter(
        AcademicYearModel.year_code == academic_year.year_code,
        AcademicYearModel.semester == academic_year.semester
    ).first()
    if db_academic_year:
        logger.warning(f"Academic year already registered with year_code: {academic_year.year_code} and semester: {academic_year.semester}")
        return error_response(message="Academic year already registered", code=400)
    
    # 创建新学年学期
    db_academic_year = AcademicYearModel(
        year_code=academic_year.year_code,
        year_name=academic_year.year_name,
        start_date=academic_year.start_date,
        end_date=academic_year.end_date,
        semester=academic_year.semester,
        status=academic_year.status,
        is_current=academic_year.is_current,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_academic_year)
    db.commit()
    db.refresh(db_academic_year)
    
    # 转换为Pydantic模型
    academic_year_response = AcademicYearInDB.model_validate(db_academic_year)
    
    logger.info(f"Academic year created successfully with ID: {db_academic_year.id}")
    return success_response(data=academic_year_response, message="Academic year created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[AcademicYearSchema]])
def read_academic_years(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching academic years with skip: {skip}, limit: {limit}")
    
    academic_years = db.query(AcademicYearModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    academic_years_response = [AcademicYearInDB.model_validate(academic_year) for academic_year in academic_years]
    total = db.query(AcademicYearModel).count()
    
    logger.info(f"Found {len(academic_years)} academic years")
    return paginated_response(
        items=academic_years_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{academic_year_id}", response_model=APIResponse[AcademicYearSchema])
def read_academic_year(academic_year_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching academic year with ID: {academic_year_id}")
    
    db_academic_year = db.query(AcademicYearModel).filter(AcademicYearModel.id == academic_year_id).first()
    if db_academic_year is None:
        logger.warning(f"Academic year not found with ID: {academic_year_id}")
        return error_response(message="Academic year not found", code=404)
    
    # 转换为Pydantic模型
    academic_year_response = AcademicYearInDB.model_validate(db_academic_year)
    
    logger.info(f"Academic year found with ID: {academic_year_id}")
    return success_response(data=academic_year_response)

@router.put("/{academic_year_id}", response_model=APIResponse[AcademicYearSchema])
def update_academic_year(academic_year_id: int, academic_year: AcademicYearUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating academic year with ID: {academic_year_id}")
    
    db_academic_year = db.query(AcademicYearModel).filter(AcademicYearModel.id == academic_year_id).first()
    if db_academic_year is None:
        logger.warning(f"Academic year not found with ID: {academic_year_id}")
        return error_response(message="Academic year not found", code=404)
    
    # 更新学年学期信息
    update_data = academic_year.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_academic_year, key, value)
    
    setattr(db_academic_year, 'update_time', datetime.utcnow())
    db.commit()
    db.refresh(db_academic_year)
    
    # 转换为Pydantic模型
    academic_year_response = AcademicYearInDB.model_validate(db_academic_year)
    
    logger.info(f"Academic year updated successfully with ID: {academic_year_id}")
    return success_response(data=academic_year_response, message="Academic year updated successfully")

@router.delete("/{academic_year_id}", response_model=APIResponse[None])
def delete_academic_year(academic_year_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting academic year with ID: {academic_year_id}")
    
    db_academic_year = db.query(AcademicYearModel).filter(AcademicYearModel.id == academic_year_id).first()
    if db_academic_year is None:
        logger.warning(f"Academic year not found with ID: {academic_year_id}")
        return error_response(message="Academic year not found", code=404)
    
    db.delete(db_academic_year)
    db.commit()
    
    logger.info(f"Academic year deleted successfully with ID: {academic_year_id}")
    return success_response(message="Academic year deleted successfully")